package utils

import (
	"io"
	"strings"

	"gitee.com/openeuler/PilotGo/sdk/logger"
	"github.com/gin-gonic/gin"
)

func ImportScript(c *gin.Context) (string, error) {
	file, _, err := c.Request.FormFile("file")
	if err == nil {
		defer file.Close()
		content, readErr := io.ReadAll(file)
		if readErr != nil {
			logger.Error("读取文件内容失败: %s", readErr.Error())
			return "", readErr
		}
		return strings.TrimSpace(string(content)), nil
	}

	bodyBuf, err := io.ReadAll(c.Request.Body)
	if err != nil {
		logger.Error("读取request body失败: %s", err.Error())
		return "", err
	}

	bodyStr := strings.TrimSpace(string(bodyBuf))
	if contentType := c.Request.Header.Get("Content-Type"); contentType != "" && strings.Contains(contentType, "multipart/form-data") {
		contentDispositionIdx := strings.Index(strings.ToLower(bodyStr), "content-disposition")
		if contentDispositionIdx != -1 {
			contentTypeIdx := strings.Index(strings.ToLower(bodyStr[contentDispositionIdx:]), "content-type")
			if contentTypeIdx != -1 {
				contentStartIdx := strings.Index(bodyStr[contentDispositionIdx+contentTypeIdx:], "\r\n\r\n")
				if contentStartIdx != -1 {
					actualStartIdx := contentDispositionIdx + contentTypeIdx + contentStartIdx + 4 // +4 是为了跳过 "\r\n\r\n"
					endBoundaryIdx := strings.Index(bodyStr[actualStartIdx:], "--")
					if endBoundaryIdx != -1 && endBoundaryIdx > 0 {
						return strings.TrimSpace(bodyStr[actualStartIdx : actualStartIdx+endBoundaryIdx]), nil
					}
				}
			}
		}
	}

	return bodyStr, nil
}
